package jmu.cyxwcy.librarymanagement.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jakarta.validation.constraints.Pattern;
import jmu.cyxwcy.librarymanagement.pojo.*;
import jmu.cyxwcy.librarymanagement.service.ICollegeService;
import jmu.cyxwcy.librarymanagement.service.IStudentsService;
import jmu.cyxwcy.librarymanagement.service.ITeachersService;
import jmu.cyxwcy.librarymanagement.service.UserService;
import jmu.cyxwcy.librarymanagement.service.impl.ClassesServiceImpl;
import jmu.cyxwcy.librarymanagement.utils.JwtUtil;
import jmu.cyxwcy.librarymanagement.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-06-25
 */
@RestController
@RequestMapping("/teacher")
public class TeachersController {
    @Autowired
    private ITeachersService iTeachersService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ICollegeService iCollegeService;

    @PostMapping("/add")
    public Result add(@RequestBody Teachers teacher){
        //查询用户
        Teachers t = iTeachersService.findByUserName(teacher.getUsername());
        if(t==null){
            Integer collegeId = iCollegeService.findIdByCollegeName(teacher.getCollegeName());
            if (collegeId==null) {
                return Result.error("学院名无效");
            }
            teacher.setCollegeId(collegeId);
            //添加用户
            User user = new User();
            user.setCategoryId(teacher.getCategoryId());
            userService.getBaseMapper().insert(user);
            teacher.setUserId(user.getUserId());
            //添加
            String md5String = Md5Util.getMD5String(teacher.getPassword());
            teacher.setPassword(md5String);
            iTeachersService.save(teacher);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{1,16}$") String username, @Pattern(regexp = "^\\S{1,16}$") String password){
        //查询用户
        Teachers teacher = iTeachersService.findByUserName(username);
        if(teacher==null){
            return Result.error("账号错误");
        }
        if(Md5Util.getMD5String(password).equals(teacher.getPassword())){
            //登录成功生成token
            Map<String,Object> claims=new HashMap<>();
//            claims.put("username",admin.getUserName());
            //获得token令牌
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestParam Integer teacherId,@RequestParam String password,@RequestHeader("Authorization") String token){
        String md5String = Md5Util.getMD5String(password);
        iTeachersService.resetPassword(teacherId,md5String);
        //更新密码后删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

    @GetMapping("/getTeacherPersonalInfo")
    public Result getTeacherPersonalInfo(@RequestParam String username){
        MPJLambdaWrapper<Teachers> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .selectAll(Teachers.class)
                .select(College::getCollegeName)
                .leftJoin(College.class, College::getCollegeId, Teachers::getCollegeId)
                .leftJoin(User.class, User::getUserId, Teachers::getUserId)
                .eq(!username.isEmpty(), Teachers::getUsername, username);
        Teachers teacher = iTeachersService.joinInfo(queryWrapper);
        return Result.success(teacher);
    }

    @GetMapping("/findByUserName")
    public Result findByUserName(@RequestParam String username){
        Teachers teacher = iTeachersService.findByUserName(username);
        return Result.success(teacher);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Teachers teacher){
        if(teacher.getPassword()!=null){
            String md5String = Md5Util.getMD5String(teacher.getPassword());
            teacher.setPassword(md5String);
        }
        Integer collegeId = iCollegeService.findIdByCollegeName(teacher.getCollegeName());
        if (collegeId==null) {
            return Result.error("学院名无效");
        }
        teacher.setCollegeId(collegeId);

        User user = userService.getById(teacher.getUserId());
        if (user != null) {
            user.setCategoryId(1);
            userService.updateById(user);
        }
        iTeachersService.updateById(teacher);
        return Result.success();
    }

    @DeleteMapping("/delete/{teacherId}")
    public Result delete(@PathVariable Integer teacherId){
        iTeachersService.removeById(teacherId);
        return Result.success();
    }

    @GetMapping("/page")
    public Result<IPage<Teachers>> findTeachersByPage(@RequestParam Integer pageNum,
                                                      @RequestParam Integer pageSize,
                                                      @RequestParam(defaultValue = "") Integer teacherId,
                                                      @RequestParam(defaultValue = "") String teacherName,
                                                      @RequestParam(defaultValue = "") String collegeName,
                                                      @RequestParam(defaultValue = "") String status,
                                                      @RequestParam(defaultValue = "") String username,
                                                      @RequestParam(defaultValue = "") String userId) {
        IPage<Teachers> page = new Page<>(pageNum, pageSize);
        MPJLambdaWrapper<Teachers> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Teachers.class)
                .selectAll(College.class)
                .leftJoin(College.class, College::getCollegeId, Teachers::getCollegeId)
                .like(teacherId!=null, Teachers::getTeacherId, teacherId)
                .like(!teacherName.isEmpty(), Teachers::getTeacherName, teacherName)
                .like(!collegeName.isEmpty(), College::getCollegeName, collegeName)
                .like(!status.isEmpty(), Teachers::getStatus, status)
                .like(!username.isEmpty(), Teachers::getUsername, username)
                .like(!userId.isEmpty(), Teachers::getUserId, userId);
        queryWrapper.orderByAsc("teacher_id");
        IPage<Teachers> pg = iTeachersService.join(page, queryWrapper);
        return Result.success(pg);
    }
}
